﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using ControlLogNamespace;

namespace BackstageMusiciansFriend
{
    public class ControlCSV
    {
        private ControlCSV()
        {
        }

        #region Nuevos Modulos
        public static void SaveChangesInCsv(List<Product> lstExportacionProductosParam, string strDestParam)
        {
            string sLinea;

            int i = 0;

            FileStream stream = null;

            StreamWriter writer = null;

            try
            {
                // Creación de archivo .csv
                stream = new FileStream(strDestParam, FileMode.OpenOrCreate, FileAccess.Write);

                // Puntero al archivo .csv
                //writer = new StreamWriter(stream, Encoding.GetEncoding("ISO-8859-1"));
                writer = new StreamWriter(stream, Encoding.UTF8);

                sLinea = "Link;Title;Header;Description;Features;Bottom;Specifications;Images;Price";
                writer.WriteLine(sLinea);
                foreach (Product objProducto in lstExportacionProductosParam)
                {
                    sLinea =    objProducto.Link + ";" +
                                objProducto.Title + ";" +
                                objProducto.Header + ";" +
                                objProducto.Description + ";" +
                                objProducto.Features + ";" +
                                objProducto.Bottom + ";" +
                                objProducto.Specifications + ";" +
                                objProducto.Images + ";" +
                                objProducto.Price;

                    writer.WriteLine(sLinea);
                }
              
            }
            catch (Exception Ex)
            {
                ControlLog.writeLog("[SaveChangesInCsv] Excepcion guardando CSV de webScrawling: " + Ex.Message);
                throw Ex;
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }
        #endregion

        public static void GuardarCSV(Product[] prod, string sDest, int iCant)
        {
            string sLinea;

            int i = 0;

            FileStream stream = null;

            StreamWriter writer = null;

            try
            {
                // Creación de archivo .csv
                stream = new FileStream(sDest, FileMode.OpenOrCreate, FileAccess.Write);

                // Puntero al archivo .csv
                //writer = new StreamWriter(stream, Encoding.GetEncoding("ISO-8859-1"));
                writer = new StreamWriter(stream, Encoding.UTF8);

                sLinea = "Link;Title;Header;Description;Features;Bottom;Specifications;Images;Price";
                writer.WriteLine(sLinea);

                while (i < iCant)
                {
                    sLinea = prod[i].Link + ";" + prod[i].Title + ";" + prod[i].Header + ";" + prod[i].Description + ";" + prod[i].Features +
                     ";" + prod[i].Bottom + ";" + prod[i].Specifications + ";" + prod[i].Images + ";" + prod[i].Price;
                    writer.WriteLine(sLinea);
                    i++;
                }
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }

        public static ProductML[] CargarDesdeCSV(string sDest, ref TinyProd[] miniprod, int iCant)
        {
            string sLinea;

            int i = 0;

            ControlLog.writeLog("[CargarDesdeCSV] FilePath de Productos a autopublicar = " + sDest + " - Cantidad: "+iCant.ToString());   
            FileStream stream = new FileStream(sDest, FileMode.Open, FileAccess.Read);

            StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("iso-8859-1")/*, Encoding.UTF8 */);

            ProductML[] prod = new ProductML[iCant];

            try
            {
             

                do
                {
                    sLinea = reader.ReadLine();

                    if (sLinea == null)
                    {
                        ControlLog.writeLog("[CargarDesdeCSV] Linea es NULL!!!!!");
                        break;
                    }

                    if (sLinea.StartsWith("Price")) //HZ Linea Header
                    {
                        continue;
                    }
                    else if (sLinea.StartsWith("$"))  //HZ : Tiene que empezar si o si con signo $, si no no es una publicacion válida.
                    {
                        prod[i] = ConvertirLineaAProducto(sLinea);

                        TinyProd auxtp = new TinyProd();

                        auxtp.Number = i + 1;
                        auxtp.Link = prod[i].Title;
                        auxtp.Price = prod[i].Price;

                        miniprod[i] = auxtp;

                        auxtp = null;

                        i++;
                    }
                    else
                    {
                        break;
                    }                    
                   
                }
                while (sLinea != null);

            }
            catch (Exception Ex)
            {
                ControlLog.writeLog("[CargarDesdeCSV] Excepcion = " + Ex.Message);           
                throw Ex;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }

            ControlLog.writeLog("[CargarDesdeCSV] Productos devueltos OK!");   
            return prod;
        }

        private static ProductML ConvertirLineaAProducto(string cadena)
        {
            string[] strArrSplitString = new string[50];

            ProductML prod = new ProductML();

            strArrSplitString = cadena.Split(new char[] { ';' }, 50);
            
            prod.Price = strArrSplitString[0];
            prod.Title = strArrSplitString[1];
            prod.Header = strArrSplitString[2];
            prod.Description = strArrSplitString[3];
            prod.Features = strArrSplitString[4];
            prod.Specifications = strArrSplitString[5];
            prod.Bottom = strArrSplitString[6];
            prod.Images = strArrSplitString[7];
            prod.Marquee_1 = strArrSplitString[8];
            prod.Marquee_2 = strArrSplitString[9];
            prod.Marquee_3 = strArrSplitString[10];
            prod.Marquee_4 = strArrSplitString[11];
            prod.Marquee_5 = strArrSplitString[12];
            prod.Marquee_6 = strArrSplitString[13];
            prod.Marquee_7 = strArrSplitString[14];
            prod.Marquee_8 = strArrSplitString[15];
            prod.Marquee_9 = strArrSplitString[16];
            prod.Marquee_10 = strArrSplitString[17];
            prod.Text_1 = strArrSplitString[18];
            prod.Text_2 = strArrSplitString[19];
            prod.Text_3 = strArrSplitString[20];
            prod.Subtitle = strArrSplitString[21];
            prod.Quantity = strArrSplitString[22];
            prod.setCurrency(strArrSplitString[23]); //PABLO: Con este método se asigna el enum correspondiente. El default será "USD"

            return prod;
        }

        public static string CrearNombreCSV(string sUrl)
        {
            int i = 31, j = 31;

            do
            {
                j++;
            } while ((j < sUrl.Length) && (sUrl[j] != '#'));

            return sUrl.Substring(i, j - i);
        }

        public static int ObtenerCantidadCSV(string sDest)
        {
            string sLinea;
            ControlLog.writeLog("[ObtenerCantidadCSV] Obteniendo cantidad de publicaciones a autopublicar");    
            int i = 0;

            FileStream stream = new FileStream(sDest, FileMode.Open, FileAccess.Read);

            StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("iso-8859-1")/*, Encoding.UTF8 */);

            sLinea = null;
            do
            {

                sLinea = reader.ReadLine();

                if (sLinea == null)
                {
                    ControlLog.writeLog("[ObtenerCantidadCSV] Linea es NULL!!!!!");
                    break;
                }

                ControlLog.writeLog("[ObtenerCantidadCSV] Linea " + i.ToString() + " = " + sLinea);
                if (sLinea.StartsWith("Price")) //HZ Linea Header
                {
                    ControlLog.writeLog("[ObtenerCantidadCSV] Header encontrado!");
                    continue;
                }
                else if (sLinea.StartsWith("$"))  //HZ : Tiene que empezar si o si con signo $, si no no es una publicacion válida.
                {
                    ControlLog.writeLog("[ObtenerCantidadCSV] Publicacion encontrada!");
                    i++;
                }
                else
                {
                    ControlLog.writeLog("[ObtenerCantidadCSV] Nada mas!");
                    break;
                }
                

            }
            while (sLinea != null);
            ControlLog.writeLog("[ObtenerCantidadCSV] Cantidad de publicaciones a autopublicar = "+i.ToString());
            return i;
        }

       
    }
}